#!/usr/bin/python
import webapp2
from modules.Predef import Predef as PRE
from modules.box import Box
from modules.contact import Contact as Con

from google.appengine.api import mail
from google.appengine.api import xmpp

class CronHandler(webapp2.RequestHandler):

    def get(self):
        Box.rockMe()
        self.notify()

    def notify(self):
        co=[]
        for x in Box.listBoxes(Running=True):
            r=x.report()
            if r is not None and len(r)>0:
                co.append(x.report())

        if len(co)>0:
            query = Con.query().fetch()
            for user in query:
                self.send( '\n\n'.join(co), user )

    def send(self, s, user):

        result = xmpp.send_message(
                user.xmpp,
                s)

        if result!=xmpp.NO_ERROR:
            logging.info("xmpp send error:")
            mail.send_mail(PRE.sender_,Pre.bare_jid(user.xmpp),PRE.topic_,s)


app = webapp2.WSGIApplication([(r'/cron/.*', CronHandler)], debug=True)
